import {
  getPurchasePage,
  purchaseAdd,
  purchaseAddBillNo,
  purchaseClose,
  purchaseDelete,
  purchaseFareAdd,
  purchaseUpdate
} from "@/api/orderManag/shipperPrepar";
import { getUserList } from "@/api/system/user";
import { DictTag } from "@/components/common/DictTag";
import { addDialog } from "@/components/ReDialog";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useRouterNavigation } from "@/router/utils";
import { getDictLabel } from "@/utils/dict";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { cloneDeep } from "@pureadmin/utils";
import dayjs from "dayjs";
import { h, onMounted, reactive, ref, toRaw } from "vue";
import { getDrkCount } from "../../common";
import editForm from "../form/index.vue";
import billForm from "../form/waybill.vue";
import type { BillItemProps, FormItemProps } from "../utils/types";
//获取供应商名称
import { getSupplierSimplePage } from "@/api/basicArchives/supplierManagement";
//获取仓库名称
import { getDepositorySimplePage } from "@/api/basicArchives/warehouseManagement";
//获取字典标签
import { useDictStoreHook } from "@/store/modules/dict";
import { dealDataExcept, dealDataRide } from "@/utils/common";
import { goodsCodeRend, goodsNameRend } from "@/utils/tableColumns";

export function useShipper(onlyMySelf: boolean) {
  const form = reactive({
    onlyMySelf: onlyMySelf, // 仅查自己数据 true是 false否
    purchaseOrderCode: undefined, // 备货订单号
    orderStatus: undefined, // 订单状态
    supplierId: undefined, // 供应商id
    depositoryId: undefined, // 仓库id
    createUserId: undefined, // 创建人id
    times: [],
    startTime: "", // 开始时间
    endTime: "" // 结束时间
  });

  const loading = ref(false);
  const dataList = ref([]);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
    pageSizes: [10, 20, 50, 100]
  });

  const tabList = ref([]);

  const columns: TableColumnList = [
    {
      fixed: "left",
      type: "expand",
      slot: "expand"
    },
    {
      label: "业务日期",
      prop: "storeCode",
      formatter: ({ gmtModified }) => dayjs(gmtModified).format("YYYY-MM-DD"),
      width: 150
    },
    {
      label: "备货订单号",
      prop: "purchaseOrderCode",
      minWidth: 180
    },
    {
      label: "供应商名称",
      prop: "supplierName",
      minWidth: 200
    },
    // fareType 运费类型 1包邮 2提前支付 3到付
    {
      label: "运费类型",
      prop: "fareType",
      minWidth: 120,
      formatter: ({ fareType }) =>
        fareType == 1 ? "包邮" : fareType == 2 ? "提前支付" : "到付"
    },
    {
      label: "状态",
      prop: "orderStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag
          dict-type="PURCHASE_STATUS"
          type={
            row.orderStatus == 1
              ? "warning"
              : row.orderStatus == 2
                ? "success"
                : row.orderStatus == 3
                  ? "primary"
                  : row.orderStatus == 4
                    ? "info"
                    : "success"
          }
          dict-value={row.orderStatus}
        />
      )
    },
    {
      label: "备货总金额",
      prop: "orderPrice",
      minWidth: 120,
      formatter: ({ orderPrice }) => dealDataExcept(orderPrice)
    },
    {
      label: "备货商品总数",
      prop: "orderNum",
      minWidth: 120
    },
    {
      label: "到货仓库",
      prop: "depositoryName",
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      label: "创建人",
      prop: "createUserName",
      width: 150
    },
    {
      label: "创建时间",
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm"),
      minWidth: 180
    },
    {
      label: "运费",
      prop: "fare",
      width: 120,
      formatter: ({ fare }) => dealDataExcept(fare) || "--"
    },
    {
      label: "备注",
      prop: "des",
      minWidth: 180,
      showOverflowTooltip: true,
      formatter: ({ des }) => des || "--"
    },
    {
      label: "操作",
      fixed: "right",
      align: "left",
      width: onlyMySelf ? 225 : 80,
      slot: onlyMySelf ? "operation" : "adminOperation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "商品名称/规格名称",
      prop: "specName",
      width: 200,
      align: "left",
      // slot: "specName",
      cellRenderer: goodsNameRend
    },
    {
      label: "商品编码/规格编码",
      prop: "specCode",
      align: "left",
      width: 150,
      // slot: "specCode",
      cellRenderer: goodsCodeRend
    },
    {
      label: "商品类型",
      prop: "goodsType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <DictTag dict-type="PRODUCT_TYPE" dict-value={row.goodsType} />
      )
    },
    {
      label: "商品进价",
      prop: "buyPrice",
      minWidth: 120,
      formatter: ({ goodsSpecBuyPrice }) => dealDataExcept(goodsSpecBuyPrice)
    },
    {
      label: "商品数量",
      prop: "amount",
      minWidth: 120
    },
    {
      label: "商品单价",
      prop: "buyPrice",
      minWidth: 120,
      formatter: ({ buyPrice }) => dealDataExcept(buyPrice)
    },
    {
      label: "金额",
      prop: "orderItemPrice",
      minWidth: 120,
      formatter: ({ orderItemPrice }) => dealDataExcept(orderItemPrice)
    },
    {
      label: "分摊金额",
      prop: "avgPrice",
      minWidth: 120,
      formatter: ({ avgPrice }) => dealDataExcept(avgPrice) || "--"
    },
    {
      label: "分摊后单价",
      prop: "avgBuyPrice",
      minWidth: 120,
      formatter: ({ avgBuyPrice }) => dealDataExcept(avgBuyPrice) || "--"
    },
    {
      label: "分摊后总价",
      prop: "avgOrderItemPrice",
      minWidth: 120,
      formatter: ({ avgOrderItemPrice }) =>
        dealDataExcept(avgOrderItemPrice) || "--"
    },
    {
      label: "已入库商品数量",
      prop: "storeAmount",
      minWidth: 120
    },
    {
      label: "待入库商品数量",
      minWidth: 120,
      formatter: row => getDrkCount(row)
    },
    {
      label: "提醒",
      prop: "orderItemStatus",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <>
          {row.orderItemStatus == 2 ? (
            <el-tag type="success" effect="plain">
              部分入库
            </el-tag>
          ) : (
            <DictTag
              dict-type="PURCHASE_STATUS"
              type={
                row.orderItemStatus == 1
                  ? "warning"
                  : row.orderItemStatus == 2
                    ? "success"
                    : row.orderItemStatus == 3
                      ? "primary"
                      : row.orderItemStatus == 4
                        ? "info"
                        : "success"
              }
              dict-value={row.orderItemStatus}
            />
          )}
        </>
      )
    }
  ];

  function resetForm(formEl) {
    if (!formEl) return;
    activeName.value = "0";
    form.orderStatus = undefined;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    if (form.times && form.times.length > 0) {
      form.startTime = form.times[0] + " 00:00:00";
      form.endTime = form.times[1] + " 23:59:59";
    } else {
      form.startTime = "";
      form.endTime = "";
    }

    const formData = cloneDeep(toRaw(form));
    delete formData.times;

    const params = {
      ...toRaw(formData),
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };

    const { data } = await getPurchasePage(params);
    dataList.value = data.records;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  function tabClick({ props }) {
    if (props.name == "0") {
      form.orderStatus = undefined;
    } else {
      form.orderStatus = Number(props.name);
    }
    activeName.value = props.name;
    onSearch();
  }

  const formRef = ref();

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}货主备货`,
      sureBtnLoading: true,
      props: {
        formInline: {
          id: row?.id ?? "",
          supplierId: row?.supplierId ?? undefined,
          depositoryId: row?.depositoryId ?? undefined,
          addItemList: row?.addItemList ?? undefined,
          updateItemList: row?.updateItemList ?? undefined,
          deleteOrderItemIds: row?.deleteOrderItemIds ?? [],
          fareType: row?.fareType ?? 1, // 运费类型 1包邮 2提前支付 3到付
          fare: row?.fare ?? undefined,
          orderNum: row?.orderNum ?? undefined,
          orderPrice: row?.orderPrice ?? undefined,
          des: row?.des ?? "",
          dataList: []
        },
        supplierList: supplierList.value,
        depositoryList: depositoryList.value
      },
      class: "hzbh",
      width: "99%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);

            // 商品判断
            let goodsList = curData.dataList;
            if (goodsList.length == 0) {
              closeLoading();
              return message("请选择备货商品", { type: "warning" });
            }

            for (let index = 0; index < goodsList.length; index++) {
              const item = goodsList[index];
              if (!item.spdj || !item.spsl) {
                closeLoading();
                return message(
                  `商品: '${item.goodsName}' 商品单价、商品数量不可为空`,
                  {
                    type: "warning"
                  }
                );
              }
            }

            const params = {
              id: curData.id, // 主键id
              supplierId: curData.supplierId, // 供应商id
              depositoryId: curData.depositoryId, // 仓库id
              fareType: curData.fareType, // 运费类型 1包邮 2提前支付 3到付
              fare: dealDataRide(curData.fare), // 运费
              orderNum: 0, // 	商品数量
              orderPrice: dealDataRide(curData.orderPrice), // 商品总价
              des: curData.des, // 备注
              addItemList: [], // 新增商品列表
              updateItemList: [], // 编辑商品列表
              deleteOrderItemIds: curData.deleteOrderItemIds // 删除商品id列表
            };

            if (title === "新增") {
              // 新增时，需要传递的参数 addItemList 不需要传 updateItemList
              let totalNum = 0;
              params.addItemList = goodsList.map(v => {
                let obj = {
                  amount: v.spsl, // 商品数量
                  avgBuyPrice: dealDataRide(v.fthdj), // 分摊后单价
                  avgOrderItemPrice: dealDataRide(v.fthzj), // 分摊后总价
                  avgPrice: dealDataRide(v.ftje), // 分摊后金额
                  buyPrice: dealDataRide(v.spdj), // 商品单价
                  orderItemPrice: dealDataRide(v.xj), // 商品小计,
                  barCode: v.barCode,
                  goodsCode: v.goodsCode,
                  goodsId: v.goodsId,
                  goodsName: v.goodsName,
                  goodsType: v.goodsType,
                  specCode: v.specCode,
                  specImageJson: v.specImageJson,
                  specName: v.specName
                };
                totalNum += Number(v.spsl);
                return obj;
              });
              params.orderNum = totalNum;
              // 实际开发先调用新增接口，再进行下面操作
              console.log("params--------新增", params);
              const { code } = await purchaseAdd(params);
              if (code == 200) {
                chores();
              } else {
                closeLoading();
              }
            } else {
              // 编辑时，需要传递的参数 updateItemList 编辑当中如果有新增的商品就 需要传递 addItemList 否则不传
              let totalNum = 0;
              goodsList.forEach(v => {
                let obj = {
                  id: v.id,
                  amount: v.spsl, // 商品数量
                  avgBuyPrice: dealDataRide(v.fthdj), // 分摊后单价
                  avgOrderItemPrice: dealDataRide(v.fthzj), // 分摊后总价
                  avgPrice: dealDataRide(v.ftje), // 分摊后金额
                  buyPrice: dealDataRide(v.spdj), // 商品单价
                  orderItemPrice: dealDataRide(v.xj), // 商品小计,
                  barCode: v.barCode,
                  goodsCode: v.goodsCode,
                  goodsId: v.goodsId,
                  goodsName: v.goodsName,
                  goodsType: v.goodsType,
                  specCode: v.specCode,
                  specImageJson: v.specImageJson,
                  specName: v.specName
                };
                totalNum += Number(v.spsl);
                if (v.type == "add") {
                  delete obj.id;
                  params.addItemList.push(obj);
                } else {
                  params.updateItemList.push(obj);
                }
              });
              params.orderNum = totalNum;
              console.log("params--------编辑", params);
              const { code } = await purchaseUpdate(params);
              if (code == 200) {
                chores();
              } else {
                closeLoading();
              }
            }
          } else {
            closeLoading();
          }
        });
      }
    });
  }

  function openBillDialog(title = "新增", row?: BillItemProps, type?: number) {
    addDialog({
      title: type == 1 ? `${title}运单号` : type == 2 ? `运费到付` : "",
      props: {
        formInline: {
          purchaseOrderId: row?.id ?? "",
          com: row?.com ?? undefined, // 承运商code
          comName: row?.comName ?? undefined, // 承运商名称
          num: row?.num ?? undefined, // 运单号
          fare: dealDataExcept(row?.fare ?? undefined), // 运费
          type // 1运单号 2运费到付
        }
      },
      width: "500px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(billForm, { ref: formRef }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as BillItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          setTimeout(() => done(), 800); // 关闭弹窗
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              let parms = {
                purchaseOrderId: curData.purchaseOrderId, // 备货单id
                com: curData.com, // 承运商code
                comName: curData.comName, // 承运商名称
                num: curData.num // 运单号
              };
              // 新增运单号
              const { code } = await purchaseAddBillNo(parms);
              if (code == 200) {
                chores();
              }
            } else {
              // 运费到付
              let parms = {
                purchaseOrderId: curData.purchaseOrderId, // 备货单id
                fare: dealDataRide(curData.fare) // 运费
              };
              const { code } = await purchaseFareAdd(parms);
              if (code == 200) {
                chores();
              }
            }
          }
          closeLoading();
        });
      }
    });
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  const { push } = useRouterNavigation();
  function openDetil(row?: FormItemProps) {
    push({
      path: `/orderManag/shipperPrepar/detail`,
      query: { id: row.id }
    });
  }

  let supplierList = ref([]);
  let depositoryList = ref([]);
  const userList = ref([]);
  /**
   * 获取公共数据，包括供应商列表和仓库列表
   * @param params - 查询参数
   */
  async function getCommon(params) {
    // 供应商列表
    getSupplierSimplePage(params).then(res => {
      supplierList.value = res.data?.records || [];
    });

    // 仓库列表
    getDepositorySimplePage(params).then(res => {
      depositoryList.value = res.data?.records || [];
    });

    // 获取用户列表
    let userParams = {
      bizType: 1,
      enableStatus: 1,
      pageNum: 1,
      pageSize: 500
    };
    getUserList(userParams).then(res => {
      userList.value = res.data?.records || [];
    });
  }

  const activeName = ref("0");

  /**
   * 获取标签字典
   * 该函数首先检查本地存储中是否存在字典列表
   * 如果不存在，则从服务器获取字典列表，并将其存储在本地存储中
   * 然后，它根据指定的键（"PURCHASE_STATUS"）从字典列表中获取标签列表
   * 最后，它将一个包含所有标签的对象添加到标签列表的开头
   * @returns {Promise<void>} 当函数完成时解析的 Promise
   */
  async function getTabDict() {
    const dictList = JSON.parse(localStorage.getItem("dictList")) || [];

    if (dictList.length > 0) {
      tabList.value = getDictLabel(dictList, "PURCHASE_STATUS");
    } else {
      const params = {
        pageNum: 1,
        pageSize: 999
      };
      const { data } = await useDictStoreHook().getDictlist(params);
      tabList.value = getDictLabel(data.records, "PURCHASE_STATUS");
    }

    const allTab = {
      itemName: "全部",
      itemValue: "0"
    };
    tabList.value.unshift(allTab);
  }

  async function handleDelete(row) {
    const res = await purchaseDelete(row.id);
    if (res.code != 200) return;
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  async function handleClose(row) {
    const res = await purchaseClose({ purchaseOrderId: row.id });
    if (res.code != 200) return;
    message(`关闭成功`, { type: "success" });
    onSearch();
  }

  onMounted(() => {
    onSearch();

    // 供应商列表
    const params = {
      status: 0,
      pageNum: 1,
      pageSize: 9999
    };
    getCommon(params);

    // 标签字典
    getTabDict();
  });

  return {
    form,
    loading,
    columns,
    childColumns,
    dataList,
    pagination,
    activeName,
    tabList,
    supplierList,
    depositoryList,
    userList,
    useRenderIcon,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    tabClick,
    handleSizeChange,
    handleCurrentChange,
    openDialog,
    openBillDialog,
    openDetil,
    handleDelete,
    handleClose
  };
}
